using System;
using System.Data;
using System.Text;
using System.Windows.Forms;
using ctsu.BaseForms;
using ctsu.Data;

namespace ctsu.Admin.BusLogic
{
	public class SearchInvestigatorController : ISearchController
	{
		public event BusinessLogicEvents.BLSelectedItemEventHandler ItemSelected;
		private FormSearchBase _form;
		private SearchInfo _si;

		private string _sortByField = "p.ID";

		public SearchInvestigatorController(FormSearchBase form, SearchInfo si)
		{
			this._form = form;  //the search form
			this._si = si;
		}

		#region ISearchController Members

		public void GenericAction(object sender, System.EventArgs e)
		{
			Control ctl = (Control)sender;
			switch (ctl.Name)
			{
				case "btnApply":
					this.Apply(sender, e);
					break;
				case "rdoProtoID":
					_sortByField = "p.ID";
					break;
				////case "rdoSPID":
				////    _sortByField = "p.SPID";
				////    break;
				case "rdoProtoNumber":
					_sortByField = "p.ProtocolNumber";
					break;
				case "rdoInvName":
					_sortByField = "i.LastName";
					break;
				case "rdoInvID":
					_sortByField = "ps.InvestigatorID";
					break;
			}
		}

		public void RunSearch(object sender, EventArgs e)
		{
			Cursor.Current = Cursors.WaitCursor;

			if (_form.SearchFields.SelectedIndex == -1)
			{
				MessageBox.Show(_form, "You must select a field to search by!", "Select Search By", MessageBoxButtons.OK, MessageBoxIcon.Stop);
				return;
			}
			string searchByField = ((ReportColumn)_form.SearchFields.SelectedItem).FieldName;

			StringBuilder sql = new StringBuilder();

			sql.Append("SELECT p.ID, p.ProtocolNumber, p.Title, " +
				"i.LastName + ', ' + i.FirstName AS Name, ps.InvestigatorID " +
				"FROM ProtocolStaff ps, Protocol p, Investigator i " +
				"WHERE ps.StaffTypeID=1 AND p.ID=ps.ProtocolID " +
				"AND i.ID= ps.InvestigatorID ");

			//add there where for the select statement
			string criteria = "";
			criteria = _form.Criteria.Text;
			if (criteria.Length > 0)
			{
				if (_form.SearchFields.Text == "Investigator ID")
				{
					sql.Append(" AND ps.InvestigatorID=" + criteria);

				}
				else if (_form.SearchFields.Text == "Last Name")
				{
					sql.Append(" AND i.LastName LIKE '" + criteria + "%'");

				}
			}
			sql.Append(" ORDER BY " + this._sortByField);
			if (this._form.Descending.Checked)
				sql.Append(" DESC ");

			//clear the listview and fill with results
			_form.SearchResults.BeginUpdate();
			_form.SearchResults.Items.Clear();

			//SqlConnection conn = LoginForm.GetSqlConnection();
			IDataReader reader = null;
			try
			{
				reader = DataAccess.GetDataReader(sql.ToString());

				while (reader.Read())
				{
					ListViewItem lvi = new ListViewItem();
					int i = 0;
					string data;
					foreach (ReportColumn rc in _si.SearchResultCols)
					{
						if (reader.IsDBNull(i))
							data = "";
						else
							data = reader[rc.FieldName].ToString();
						if (i == 0)
							lvi.Text = data;
						else
							lvi.SubItems.Add(data);
						i++;
					}
					_form.SearchResults.Items.Add(lvi);
				}

				//resize the listview columns according to the results
				foreach (ColumnHeader ch in _form.SearchResults.Columns)
					ch.Width = -2;

			}
			catch
			{
			}
			finally
			{
				if (reader != null)
				{
					if (!reader.IsClosed)
						reader.Close();
				}
				//if(conn != null)
				//    conn.Dispose();
				_form.SearchResults.EndUpdate();
			}
		}

		public void SearchFieldsChanged(object sender, EventArgs e)
		{
			// TODO:  Add SearchInvestigatorController.SearchFieldsChanged implementation
		}

		#endregion

		#region IFormClose Members
		public void Apply(object sender, System.EventArgs e)
		{
			//
			ListView lvw = _form.SearchResults;
			if (lvw.Items.Count > 0)
			{
				if (lvw.SelectedItems.Count == 0)
				{
					MessageBox.Show(_form, "Select a row!", "Select Row",
						MessageBoxButtons.YesNo, MessageBoxIcon.Stop);
					return;
				}
				//this depends on the first column (id) being an int
				ListViewItem lvi = lvw.SelectedItems[0];
				_form.SelectedID = Convert.ToInt32(lvi.Text);

				BLReturnIDEventArgs args = new BLReturnIDEventArgs("", _form.SelectedID);
				if (ItemSelected != null)
					ItemSelected(this, args);
			}
			else
				_form.SelectedID = -1;
		}

		public void Accept(object sender, System.EventArgs e)
		{
			//
			ListView lvw = _form.SearchResults;
			if (lvw.Items.Count > 0)
			{
				if (lvw.SelectedItems.Count == 0)
				{
					MessageBox.Show(_form, "Select a row!", "Select Row",
						MessageBoxButtons.YesNo, MessageBoxIcon.Stop);
					return;
				}
				//this depends on the first column (id) being an int
				ListViewItem lvi = lvw.SelectedItems[0];
				_form.SelectedID = Convert.ToInt32(lvi.Text);

				BLReturnIDEventArgs args = new BLReturnIDEventArgs("", _form.SelectedID);
				if (ItemSelected != null)
					ItemSelected(this, args);

				_form.DialogResult = DialogResult.OK;

				_form.Close();
			}
			else
				_form.SelectedID = -1;
		}

		public void Cancel(object sender, System.EventArgs e)
		{

			_form.SelectedID = -1;
			_form.Close();
		}

		public void Exit(object sender, System.EventArgs e)
		{

		}

		public void Closing(object sender, System.ComponentModel.CancelEventArgs e)
		{

		}
		#endregion
	}
}
